package com.xxkj.drugtraceability.ui.departdrug

import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.View
import android.view.ViewParent
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import com.xxhis.refactor.eventbus.MessageCode
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.databinding.ActivityDepartDrugcollectionBinding
import com.xxkj.drugtraceability.databinding.LayoutDepartCollectTopViewBinding
import com.xxkj.drugtraceability.databinding.LayoutDrupCollectTopViewBinding
import com.xxkj.drugtraceability.dialog.BlueDialog
import com.xxkj.drugtraceability.dialog.YellowDialog
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.lifecycle.KtxManager
import com.xxkj.drugtraceability.scan.BarcodeType
import com.xxkj.drugtraceability.utils.showCompleteToast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * author: zhoujingjin
 * created on: 2024/12/02 11:43
 * description:病区领药追溯
 */
class DepartDrugActivity:BaseVMActivity() {
    private val binding by binding<ActivityDepartDrugcollectionBinding>(R.layout.activity_depart_drugcollection)
    private val viewModel by viewModel<DepartDrugCollectionViewModel>()
    override fun initView() {
        binding.apply {
            toolBar.title = ""
            setSupportActionBar(toolBar)
            toolBar.setNavigationOnClickListener {
                onBackPressed()
            }
            viewModel.mFragmentList.add(DepartDrugFragment.newInstance(0))
            viewModel.mFragmentList.add(DepartDrugFragment.newInstance(1))
            binding.viewPager.adapter = mAdapter
            viewPager.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
                override fun onPageScrollStateChanged(state: Int) {

                }

                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                override fun onPageSelected(position: Int) {
                    viewModel.viewpagerIndex.postValue(position)
                }
            })
            llWei.clickN {
                if (viewModel.viewpagerIndex.value!=0){
                    binding.viewPager.currentItem = 0
                }
            }
            llYi.clickN {
                if (viewModel.viewpagerIndex.value!=1){
                    binding.viewPager.currentItem = 1
                }
            }
            tvCancel.clickN {
                YellowDialog(this@DepartDrugActivity,resources.getString(R.string.cancel_all)){
                    //清空所有追溯码
                    finish()
                }
            }
            tvClear.clickN {
                YellowDialog(this@DepartDrugActivity,resources.getString(R.string.clear_all)){
                    //清空所有追溯码
                    var data1 = viewModel.dataList.value
                    var data2 = viewModel.unDataList.value
                    data1?.forEach {
                        it.drugTracInfos?.clear()
                    }
                    data2?.forEach {
                        it.drugTracInfos?.clear()
                        data1?.add(it)
                    }
                    viewModel.unDataList.postValue(data1)
                    viewModel.dataList.postValue(mutableListOf())
                }
            }
            tvSave.clickN {
                var alert = false
                var noData = true
                var dataList = mutableListOf<DepartDrugInfo>()
                viewModel.dataList.value?.forEach {
                    if (!it.drugTracInfos.isNullOrEmpty()){
                        noData = false
                    }
                    dataList.add(it)
                    if(it.drugTracInfos?.size!=it.fysl?.toDouble()
                            ?.toInt()){
                        alert = true
                    }
                }
                viewModel.unDataList.value?.forEach {
                    if (!it.drugTracInfos.isNullOrEmpty()){
                        noData = false
                    }
                    dataList.add(it)
                    if(it.drugTracInfos?.size!=it.fysl?.toDouble()
                            ?.toInt()){
                        alert = true
                    }
                }
                if (noData){
                    //提示没有任何数据
                    YellowDialog(this@DepartDrugActivity,resources.getString(R.string.no_data),type = 1){

                    }
                }else{
                    if (alert){
                        BlueDialog(this@DepartDrugActivity,resources.getString(R.string.scan_not_all)){
                            //保存数据
                            viewModel.finishScanDrugCode(FinishDepartRequest(dataList))
                        }
                    }else{
                        //保存数据
                        viewModel.finishScanDrugCode(FinishDepartRequest(dataList))
                    }
                }
            }
        }
    }

    override fun initData() {
//        viewModel.prescriptioninfo.postValue(mutableListOf())
    }

    override fun startObserve() {
        viewModel.departData.observe(this, Observer {
            if (it!=null){
                binding.sll.visibility = View.VISIBLE
                binding.viewPager.visibility = View.VISIBLE
                binding.tvName.text = it.bqmc
                binding.tvDate.text = "发药流水号：${it.fylsh}"
                if (viewModel.canAdd){
                    binding.llBottom.visibility = View.VISIBLE
                }else{
                    binding.llBottom.visibility = View.GONE
                }
            }else{
                binding.sll.visibility = View.GONE
                binding.viewPager.visibility = View.GONE
                binding.llBottom.visibility=View.GONE
            }

        })
        viewModel.viewpagerIndex.observe(this, Observer {
            when(it){
                0->{
                    binding.svWei.visibility=View.VISIBLE
                    binding.tvWei.setTypeface(null, Typeface.BOLD) // 加粗
                    binding.tvYi.setTypeface(null, Typeface.NORMAL)
                    binding.svYi.visibility=View.INVISIBLE
                }
                1->{
                    binding.svWei.visibility=View.INVISIBLE
                    binding.svYi.visibility=View.VISIBLE
                    binding.tvWei.setTypeface(null, Typeface.NORMAL) // 加粗
                    binding.tvYi.setTypeface(null, Typeface.BOLD)
                }
            }
        })
        viewModel.baseUiModel.observe(this, Observer {
            if (it.showLoading){
                showMyDialog(resources.getString(R.string.getting_data))
            }else{
                dismissMyDialog()
            }
            if (!it.showError.isNullOrEmpty()){
                BlueDialog(this,it.showError!!,type = 1){}
            }
            if (it.showSuccess==true){
                showCompleteToast(this)
            }
        })
//        viewModel.prescriptioninfo.observe(this, Observer { list->
////            if (!list.isNullOrEmpty()&& list.isNotEmpty()){
////                val prescr = list[0]
////                prescr.let {
////                    adapter.setCanScan(viewModel.canAdd)
////                    if (viewModel.canAdd){
////                        binding.llBottom.visibility = View.VISIBLE
////                    }else{
////                        binding.llBottom.visibility = View.GONE
////                    }
////                    if (it==null){
////                        adapter.removeAllHeaderView()
////                        adapter.setList(mutableListOf())
////                    }else{
////                        val view =  LayoutInflater.from(this).inflate(R.layout.layout_depart_collect_top_view,null)
////                        val bind = DataBindingUtil.bind<LayoutDepartCollectTopViewBinding>(view)
////                        bind?.apply {
////                            tvDate.text = it.fylsh
////                            tvName.text = it.bqmc
////                        }
////                        adapter.addHeaderView(view)
////
////                    }
////
////                }
////                if (list.isNullOrEmpty()){
////                    adapter.setList(mutableListOf())
////                    adapter.setEmptyView(R.layout.layout_nodata)
////                }else{
////                    adapter.setList(list)
////                }
////            }else{
////                binding.llBottom.visibility = View.GONE
////                adapter.removeAllHeaderView()
////                adapter.setEmptyView(R.layout.layout_nodata)
////                adapter.setList(mutableListOf())
////                viewModel.selectIndex.value = -1
////            }
//
//        })

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: EventMessage?) {
        message?.apply {
            //扫码拿到barcode了，去请求接口
            when (message.messageCode) {
                MessageCode.SCAN_BARCODE -> {
                    if (KtxManager.isTopActivity(this@DepartDrugActivity)){
                        val barcodeMessage = this.any as BarcodeMessage
                        if (viewModel.Prescriptionbarcode.isEmpty()){
                            //无值扫的算处方码
                            viewModel.getPrescriptionInfo(barcodeMessage.barcode)
                        } else{
                            if(barcodeMessage.type== BarcodeType.SUYUAN){
                                if (viewModel.canAdd){
                                    //扫码去
                                    viewModel.trugTracCodgIsGather(barcodeMessage.barcode)
                                }
                            }else{
                                YellowDialog(this@DepartDrugActivity,resources.getString(R.string.scan_suyuan),type = 1){}
                            }

                        }
                    }
                }
            }
        }
    }
    private val mAdapter: FragmentPagerAdapter =
        object : FragmentPagerAdapter(supportFragmentManager) {
            override fun getCount(): Int {
                return viewModel.mFragmentList.size
            }

            override fun getItem(arg0: Int): Fragment {
                return viewModel.mFragmentList[arg0]
            }
        }
    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}